<!--甘特图首页-->
<template>
  <div class="gantt-table">
    <div class="gantt-head">
      <!-- 头部-->
      <div class="gantt-fixed">
        <div class="gantt-head">
          <span>时间区间</span>
          <span>
            {{
              `${new Date(choiceTime[0]).format('yyyy-MM-dd')} 
                  -  
                  ${new Date(choiceTime[1]).format('yyyy-MM-dd')}`
            }}
          </span>
        </div>
      </div>
    </div>
    <div class="gantt-box">
      <div class="left" ref="left">
        <div class="head">
          <!--    左边栏的列表头      -->
          <div class="head-box">
            <GanttRow>
              <GanttBlock>序号</GanttBlock>
              <GanttBlock>编号</GanttBlock>
              <!-- <GanttBlock>机号</GanttBlock> -->
            </GanttRow>
          </div>
        </div>
        <!--  左边栏的列表内容      -->
        <div
          class="left-box"
          :style="{ transform: `translateY(-${transFormYValue}px)` }"
        >
          <!--虚拟列表padding展位 虚假的padding-top-->
          <div
            class="virtual-padding"
            :style="{ height: virtual.paddingTop + 'px' }"
          ></div>
          <GanttRow
            v-for="(item, index) in virtualGanttData"
            :overActive="overAction"
            :key="index"
            :style="{
              height: item.height + 'px',
            }"
          >
            <GanttBlock>{{ item.id }}</GanttBlock>
            <GanttBlock>{{ item.type }}</GanttBlock>
            <!-- <GanttBlock>{{ item.code }}</GanttBlock> -->
          </GanttRow>

          <!--虚拟列表padding展位 虚假的padding-bottom-->
          <div
            class="virtual-padding"
            :style="{ height: virtual.paddingBottom + 'px' }"
          ></div>
        </div>
      </div>
      <!--    右边的内容      -->
      <div
        class="right"
        ref="right"
        @contextmenu.prevent="cancelRightClick"
        @click="cancelRightClick"
      >
        <!--  时间头      -->
        <div class="head">
          <div class="head-box">
            <GanttRow
              :style="{ transform: `translatex(-${transFormXValue}px)` }"
              class="transition-transForm"
            >
              <GanttTimeBlock
                :target-time="item.format('yyyy-MM-dd')"
                v-for="(item, index) in choiceTimeArr"
                :key="index"
              ></GanttTimeBlock>
            </GanttRow>
          </div>
        </div>
        <div class="content" id="contentGrid">
          <div class="content-box" ref="contentGrid">
            <!--      甘特图中具体的内容   -->
            <div class="gantt-grid" ref="box" id="ganttGrid">
              <!--虚拟列表padding展位 虚假的padding-top-->
              <div
                class="virtual-padding"
                :style="{ height: virtual.paddingTop + 'px' }"
              ></div>

              <!--   网格状图表  -->
              <GanttRow
                v-for="(item, rowIndex) in virtualGanttData"
                :key="item.id"
                :id="`ganttRow-${rowIndex}`"
                class="gantt-row-relative"
                :overActive="overAction"
                @mouseOver="() => rowMouseOver(item)"
                :hidden="item.isHidden"
                :class="{
                  'gantt-row-active': nowSuck.id === item.id && overAction,
                }"
                :style="{
                  height: item.height + 'px',
                }"
              >
                <template v-if="item.timeBlock">
                  <!--可操作模块-->
                  <!-- <action-block
                    enableDragSide
                    enableDragFree
                    v-for="(times, timeIndex) in item.timeBlock"
                    :key="times.id"
                    :blockData="times"
                    :ganttData="ganttData"
                    :rowData="item"
                    startTimeCol="startTime"
                    endTimeCol="endTime"
                    :scrollLeft="transFormXValue"
                    @moveSideChange="() => doTier(item)"
                    @onActionBlockDown="() => doActionBlockDown(item)"
                    :scrollTop="transFormYValue"
                    :choiceTime="choiceTime"
                  > -->
                  <action-block
                    enableDragSide
                    enableDragFree
                    v-for="(times, timeIndex) in item.timeBlock"
                    :key="times.id"
                    :blockData="times"
                    :ganttData="ganttData"
                    :rowData="item"
                    startTimeCol="startTime"
                    endTimeCol="endTime"
                    :scrollLeft="transFormXValue"
                    :scrollTop="transFormYValue"
                    :choiceTime="choiceTime"
                  >
                    <div
                      class="time-block"
                      @contextmenu.prevent.stop="rightClick(times, $event)"
                    >
                      {{ times.id }}
                    </div>
                  </action-block>
                </template>
                <!--      block => 180  因为timeBlock => 60    60*3 = 180px   -->
                <GanttBlock
                  v-for="rowIndex in (24 / 3) * choiceTimeArr.length"
                  :key="rowIndex"
                  style="flex-shrink: 0"
                ></GanttBlock>
              </GanttRow>

              <!--虚拟列表padding展位 虚假的padding-bottom-->
              <div
                class="virtual-padding"
                :style="{ height: virtual.paddingBottom + 'px' }"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--右键菜单   -->
    <context-menu
      :is-show="rightMenu.isShow"
      :left.sync="rightMenu.left"
      :top.sync="rightMenu.top"
    >
      <context-menu-item title="零件编号：当前工序"></context-menu-item>
      <context-menu-item title="当前工序：当前工序"></context-menu-item>
      <context-menu-item title="订单编号：订单编号"></context-menu-item>
      <context-menu-item title="产品编号：产品编号"></context-menu-item>
      <context-menu-item title="开始时间：开始时间"></context-menu-item>
      <context-menu-item title="结束时间：结束时间"></context-menu-item>
    </context-menu>
  </div>
</template>

<script>
  import GanttRow from '../gantt/gantt-row'
  import GanttBlock from '../gantt/gantt-block'
  import GanttTimeBlock from '../gantt/gantt-time-block'
  import ganttMixin from '../gantt/mixin/gantt-mixin'
  import ganttVirtual from '../gantt/mixin/gantt-virtual'
  import airPlaneData from '../fake-data/airPlaneData.js'
  import ActionBlock from '../gantt/action-block'
  import ContextMenu from '../context-menu/context-menu'
  import ContextMenuItem from '../context-menu/context-menu-item'
  import { EventBus } from '../common/js/util'
  import { PartInfo, DeviceRunningRate } from '@/api/production'
  import View from '@/views/other/iframe/view.vue'
  export default {
    props: {
      type: {
        type: String,
        default: 1,
      },
    },
    name: 'gantt-index',
    mixins: [ganttMixin, ganttVirtual],
    components: {
      ContextMenuItem,
      ContextMenu,
      ActionBlock,
      GanttBlock,
      GanttRow,
      GanttTimeBlock,
    },
    data() {
      return {
        //选择的时间区间
        choiceTime: ['2024-02-23 00:00:00', '2024-02-23 00:00:00'],
        nowSuck: {
          id: null,
        },
        //用于判断 当前移动到的行，用于磁性吸附
        offsetTopArr: [],
        //默认的高度
        defaultTop: 10,

        overAction: false,
      }
    },
    computed: {},
    methods: {
      //加载数据
      getData() {
        // let arr = airPlaneData

        // let arr = this.airPlaneData
        // console.log('this.airPlaneData', this.airPlaneData)
        //在此处进行防重叠计算
        DeviceRunningRate().then((res) => {
          console.log('resres', res)
          let arr = airPlaneData
          arr.forEach((big) => {
            big.isHidden = false

            big.isVirtual = false
            //对每一条计算层级
            this.handleSingleFold(big, 'startTime', 'endTime')
          })
          console.log('arrarr', arr)
          let data = res.MachineDeviceGroupRunnningRateInfo.map((v, i) => {
            let obj = {
              type: v.DeviceId,
              id: i,
              code: '21',
              height: 50,
              isHidden: false,
              isVirtual: true,
              layout: '',
              timeBlock: v.DeviceProductRunningList
                ? v.DeviceProductRunningList.map((vv) => {
                    let obj = {
                      id: vv.MaterialId,
                      startTime: this.setDate(vv.StartTime),
                      endTime: this.setDate(vv.EndTime),
                    }
                    return obj
                  })
                : [],
            }
            return obj
          })
          console.log('datadata', data)
          this.ganttData = arr

          this.getVirtualList()
        })
      },
      setDate(time) {
        time = time ? time : new Date()
        let DateObj = new Date(time)
        // 将时间转换为 XX年XX月XX日XX时XX分XX秒格式
        let year = DateObj.getFullYear()
        let month = DateObj.getMonth() + 1
        let day = DateObj.getDate()
        let hh = DateObj.getHours()
        let mm = DateObj.getMinutes()
        let ss = DateObj.getSeconds()
        month = month > 9 ? month : '0' + month
        day = day > 9 ? day : '0' + day
        // 最终时间2021/07/29 5:50:24
        let date = `${year}/${month}/${day} ${hh}:${mm}:${ss}`
        return date
      },
      //时间条拉伸
      doTier(v) {
        //让右键菜单消失
        this.rightMenu.isShow = false
        this.handleSingleFold(v, 'startTime', 'endTime')
      },
      doActionBlockDown(row) {
        this.overAction = true
      },
      doActionBlockUp(row) {
        this.overAction = false
      },
      rowMouseOver(row) {
        //让右键菜单消失
        this.rightMenu.isShow = false

        this.overAction = true

        this.nowSuck = JSON.parse(JSON.stringify(row))
      },
      //时间块移动后鼠标松开，进行磁性吸附
      doFreeMoveUp(obj, row) {
        this.overAction = false

        //如果nowSuck为-1 说明没有进行移动
        if (this.nowSuck.id == null) {
          return
        }

        // 操作的这个块，在row中的位置 仅用于删除用
        const timeIndex = row.timeBlock.findIndex((e) => e.id === obj.id)

        //原数据删除
        row.timeBlock.splice(timeIndex, 1)

        //防碰撞渲染
        this.handleSingleFold(row, 'startTime', 'endTime')

        // 当前nowSuck 是 json化后的
        // 需要取得 与 ganttData有关联的哪个 nowSuck数据
        const targetRow = this.ganttData.find((e) => e.id === this.nowSuck.id)

        //新数据放置
        targetRow.timeBlock.push(obj)

        //防碰撞渲染
        this.handleSingleFold(targetRow, 'startTime', 'endTime')
        //时间块重新部署完成，nowSuck重置
        this.nowSuck.id = null
      },
      //右键点击
      rightClick(times, event) {
        let delay = 0

        //如果是已经是展开状态，如果再展开，那就延时一下，让菜单消失的不那么突兀
        if (this.rightMenu.isShow == true) {
          delay = 150
          this.cancelRightClick()
        }
        setTimeout(() => {
          this.rightMenu.isShow = true

          this.rightMenu.left = event.clientX

          this.rightMenu.top = event.clientY
        }, delay)
      },
      //取消右键点击
      cancelRightClick() {
        this.rightMenu.isShow = false
      },
      getTodayStartAndEnd() {
        const now = new Date()
        const year = now.getFullYear()
        const month = now.getMonth()
        const day = now.getDate()

        // 设置当日开始时间为00:00:00
        const start = new Date(year, month, day, 0, 0, 0)
        // 设置当日结束时间为23:59:59
        const end = new Date(year, month, day, 23, 59, 59)

        // this.todayStart = start.toISOString() // 转换为ISO字符串格式
        // this.todayEnd = end.toISOString()
        this.choiceTime = [start.toISOString(), end.toISOString()]
      },
    },
    mounted() {
      this.getTodayStartAndEnd()
      //开始滚动交互事件
      this.getScrollEvent()
      this.getData()

      EventBus.$on('onActionBlockUp', (param) => {
        this.doFreeMoveUp(param.blockData, param.rowData)
      })
    },
  }
</script>

<style scoped lang="scss">
  @import '../common/css/global-property';

  .gantt-table {
    .gantt-head {
      width: 100%;
      height: $topBarHeight;

      .gantt-fixed {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: $topBarHeight;

        background-image: $topBarColor;
        .gantt-head {
          padding-left: 15px;
          font-weight: bold;
          line-height: $topBarHeight;
          color: $tableHeadColor;
        }
      }
    }

    .gantt-box {
      display: flex;
      width: 100%;
      height: calc(100vh - #{$topBarHeight});
      .left {
        width: $leftSideWidth;
        overflow: hidden;

        .head {
          height: $tableHeadHeight;
          position: relative;
          z-index: 3;
          .head-box {
            background-color: $tableHeadColor;
            height: $tableHeadHeight;
            color: $tableHeadFontColor;
            width: 100%;
          }
        }
        .left-box {
          background-color: $tableLeftColor;
        }
      }

      .right {
        flex: 1;
        min-width: 0;
        .head {
          height: $tableHeadHeight;
          .head-box {
            overflow: hidden; //transform 移动出的东西 隐藏
            box-sizing: border-box;
            color: $tableHeadFontColor;
            background-color: $tableHeadColor;
            height: $tableHeadHeight;
            z-index: 2;
          }
        }

        .content {
          height: calc(100% - #{$tableHeadHeight});
          //overflow-x: auto;
          position: relative;
          .content-box {
            height: 100%;
            overflow-x: auto;
            position: relative;
          }
          .gantt-grid {
            //position: relative;
            display: inline-block;
            overflow: hidden;
            z-index: 1;

            .gantt-row-relative {
              position: relative;
              transition: background-color 0.2s;
              &.gantt-row-active {
                background-color: $tableRowActiveColor;
              }
              //时间块的样式
              .time-block {
                height: 100%;
              }
            }
          }
        }
      }
    }
  }
</style>
